package com.cuoyi.coupon.mall.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Arrays;
import java.util.List;

/**
 * swagger 文档尽量进行分组，这里基于 调用方 分成了4组 app,admin,mini,h5
 *
 * @author zhang.cheng
 */
@EnableOpenApi
@Configuration
public class Swagger3Config {

    @Value("${spring.application.name}")
    private String appName;

    @Bean
    public Docket appRestApi() {
        return new Docket(DocumentationType.OAS_30).globalRequestParameters(headers()).apiInfo(apiInfo("app")).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.any()).paths(PathSelectors.ant("/app/**")).build().groupName("app");
    }

    @Bean
    public Docket adminRestApi() {
        return new Docket(DocumentationType.OAS_30).globalRequestParameters(headers()).apiInfo(apiInfo("admin")).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.any()).paths(PathSelectors.ant("/admin/**")).build().groupName("admin");
    }

    private ApiInfo apiInfo(String entry) {
        return new ApiInfoBuilder().title(appName + " " + entry + "").version("1.0").description(appName).build();
    }

    private List<RequestParameter> headers() {
        RequestParameter token = new RequestParameterBuilder().name("token").description("用户token").in(ParameterType.HEADER).required(false).query(param -> param.model(model -> model.scalarModel(ScalarType.STRING))).build();
        RequestParameter userId = new RequestParameterBuilder().name("userid").description("用户Id").in(ParameterType.HEADER).required(false).query(param -> param.model(model -> model.scalarModel(ScalarType.STRING))).build();
        RequestParameter brandCode = new RequestParameterBuilder().name("brandCode").description("品牌").in(ParameterType.HEADER).required(false).query(param -> param.model(model -> model.scalarModel(ScalarType.INTEGER))).build();
        return Arrays.asList(token, userId, brandCode);
    }
}
